
package boids;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

import processing.core.PGraphics;

public class Environment2D implements ProcessingRenderable
{
	private ArrayList<Boid2D>				boids;
	private ArrayList<Obstacle>			obstacles;
	private HashMap<Boid2D, SplinePath>	boidPaths;
	private SplinePath						globalPath;

	private float								width;
	private float								height;

	public Environment2D(float _width, float _height)
	{
		boids = new ArrayList<Boid2D>();
		obstacles = new ArrayList<Obstacle>();
		boidPaths = new HashMap<Boid2D, SplinePath>();

		width = _width;
		height = _height;
	}

	public void addBoid(Boid2D _boid)
	{
		_boid.setEnvironment(this);
		boids.add(_boid);
	}

	public Boid2D getBoid(int _index)
	{
		// TODO: rewrite using exceptions…
		if (_index >= 0 && _index < boids.size())
		{
			return boids.get(_index);
		}
		System.err.println("WARNING: You were trying to access a Boid that did not exits! The newest one was returned!");
		return boids.get(boids.size() - 1);
	}

	public void assignPathToBoid(Boid2D _boid, SplinePath _path)
	{
		boidPaths.put(_boid, _path);
	}

	public SplinePath getPathForBoid(Boid2D _boid)
	{
		if (boidPaths.containsKey(_boid))
		{
			return boidPaths.get(_boid);
		}
		else
		{
			return null;
		}
	}

	public int getNumBoids()
	{
		return boids.size();
	}

	public void setGlobalPath(SplinePath _globalPath)
	{
		globalPath = _globalPath;
	}

	public SplinePath getGlobalPath()
	{
		return globalPath;
	}

	public ArrayList<Obstacle> getObstacles()
	{
		return obstacles;
	}

	public void render(PGraphics _g)
	{
		if (globalPath != null)
		{
			globalPath.render(_g);
		}

		Set<Boid2D> boids = boidPaths.keySet();
		for (Iterator i = boids.iterator(); i.hasNext();)
		{
			Boid2D boid = (Boid2D) i.next();
			boidPaths.get(boid).render(_g);
		}
	}
}
